#ifndef __M_ONLINE_H__
#define __M_ONLINE_H__

#pragma once

#include "util.hpp"
#include <mutex>
#include <unordered_map>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

class online_manager
{
public:
    void enter_hall(uint64_t uid, wsserver_t::connection_ptr& conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _halluser.insert(std::make_pair(uid, conn));
    }

    void enter_room(uint64_t uid, wsserver_t::connection_ptr& conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _roomuser.insert(std::make_pair(uid, conn));
    }

    void exit_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _halluser.erase(uid);
    }

    void exit_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _roomuser.erase(uid);
    }

    bool is_in_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        if (_halluser.find(uid) == _halluser.end())
            return false;
        return true;
    }

    bool is_in_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        if (_roomuser.find(uid) == _roomuser.end())
            return false;
        return true;
    }

    wsserver_t::connection_ptr get_conn_from_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _halluser.find(uid);
        if (it == _halluser.end())
            return wsserver_t::connection_ptr();
        return it->second;
    }

    wsserver_t::connection_ptr get_conn_from_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _roomuser.find(uid);
        if (it == _roomuser.end())
            return wsserver_t::connection_ptr();
        return it->second;
    }

private:
    std::mutex _mutex;
    std::unordered_map<uint64_t, wsserver_t::connection_ptr> _halluser;
    std::unordered_map<uint64_t, wsserver_t::connection_ptr> _roomuser;
};

#endif